<template>
  <div class="home">
    <van-nav-bar :title="chartRoomName">
      <template #right>

        <!-- <van-button  
                    size="mini"
                    icon="friends-o">{{onlineUserList.length}}人</van-button> -->
        <van-badge :content="onlineUserList.length">
          <van-icon name="friends-o"
                    size="18"
                    @click="showOnlineUserPopup=true" />
        </van-badge>

      </template>
    </van-nav-bar>
    <!-- {{user}} -->
    <div class="content">
      <div v-for="(item,i) in msgList"
           :key="i"
           class="card"
           :class="item.chatUser.account==user.account?'right':'left'">

        <div class="message">

          <div v-if="item.type==1"
               @click="selectMessageHandle(item)">{{item.message}}</div>
          <template v-else-if="item.type==2"><img :src="item.message"></template>

        </div>
        <div class="van-hairline--top"></div>
        <div style=""
             class="chat-info">
          <span style="color: #f9e02a;"
                v-if="currentGroup.adminId==item.chatUser.id">群主</span>
          <span style="opacity: 1;">{{item.chatUser.nickName}}</span>
          <span style="opacity: 0.6;">{{item.chatUser.userAgent}}</span>
          <span style="opacity: 0.6;">{{moment(item.dateTime)}}</span>

        </div>
      </div>

      <div id="aa"></div>
    </div>

    <div class="footer">
      <template v-if="online">
        <div style="flex:1;padding-right:20px">
          <input type="text"
                 v-model="message"
                 @keypress="messageKeyPressHandle">
        </div>
        <div>

          <van-button type="primary"
                      size="small"
                      style="margin-right:10px"
                      @click="sendMessage">发送</van-button>
          <van-button type="primary"
                      size="small"
                      @click="imgPopup.show=true">图片</van-button>

        </div>
      </template>
      <div style="text-align:center;flex: 1;"
           v-else>
        加载中
      </div>
    </div>
    <van-popup class="popup"
               :show="loginPopup.show"
               round
               position="bottom"
               :style="{ height: '240px' }">
      <!-- <div class="title">请登录</div> -->
      <div>
        <van-tabs v-model:active="active">
          <van-tab title="登录">
            <van-form @submit="loginHandle">
              <van-cell-group inset>
                <van-field v-model="loginPopup.login.account"
                           name="account"
                           label="用户名"
                           placeholder="用户名"
                           :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model="loginPopup.login.password"
                           type="password"
                           name="password"
                           label="密码"
                           placeholder="密码"
                           :rules="[{ required: true, message: '请填写密码' }]" />
              </van-cell-group>
              <div style="margin: 16px;">
                <van-button round
                            block
                            type="primary"
                            native-type="submit">
                  提交
                </van-button>
              </div>
            </van-form>
          </van-tab>
          <van-tab title="注册">
            <van-form @submit="registHandle">
              <van-cell-group inset>
                <van-field v-model="loginPopup.regist.nickName"
                           name="nickName"
                           label="昵称"
                           placeholder="昵称"
                           :rules="[{ required: true, message: '请填写昵称' }]" />
                <van-field v-model="loginPopup.regist.account"
                           name="account"
                           label="用户名"
                           placeholder="用户名"
                           :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model="loginPopup.regist.password"
                           type="password"
                           name="password"
                           label="密码"
                           placeholder="密码"
                           :rules="[{ required: true, message: '请填写密码' }]" />
              </van-cell-group>
              <div style="margin: 16px;">
                <van-button round
                            block
                            type="primary"
                            native-type="submit">
                  提交
                </van-button>
              </div>
            </van-form>
          </van-tab>
        </van-tabs>

      </div>
    </van-popup>

    <van-action-sheet v-model:show="msgPopup.show"
                      title="请选择你的操作"
                      :actions="msgPopup.actions"
                      @select="onSelectMessageAction" />

    <van-action-sheet v-model:show="imgPopup.show"
                      title="图片模式">
      <div class="img-popup-warpper">
        <van-cell-group>

          <van-cell title="单元格">
            <template #title>
              <van-field v-model="imgPopup.src"
                         center
                         clearable
                         placeholder="请输入图片链接">

              </van-field>
            </template>

            <template #value>
              <van-button size="small"
                          type="primary"
                          @click="sendImgSrc">发送图片</van-button>
              <!-- <van-field v-model="imgPopup.src"
                       center
                       clearable
                       placeholder="请输入图片链接">
              <template #button>
              
              </template>
            </van-field> -->
            </template>
          </van-cell>
          <van-cell title="选择图片"
                    label="选取当前手机上的图片发送">
            <template #value>
              <van-uploader :after-read="afterReadHandle"
                            :max-size="1024 * 1024"
                            @oversize="onOversize">
                <van-button type="primary"
                            block
                            size="small">选择图片</van-button>
              </van-uploader>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </van-action-sheet>

    <van-popup v-model:show="showOnlineUserPopup"
               position="right"
               :style="{ width: '70%' ,height:'100%'}">
      <!-- <div class="title">请登录</div> -->
      <div>
        <van-cell-group>

          <van-cell v-for="(item,i) in onlineUserList"
                    :key="i"
                    :title="item.NickName"
                    :label="item.UserAgent" />
        </van-cell-group>
      </div>
    </van-popup>

  </div>
</template>

<script >

import { ref, nextTick } from 'vue'
import * as SignalR from '@microsoft/signalr'
import { Notify, Toast } from 'vant';
import moment from 'moment'
import useClipboard from 'vue-clipboard3'
export default {
  name: 'Home',
  components: {
  },
  computed: {
    moment () {
      return function (time) {
        return moment(time).format("HH:mm:ss")
      }
    }
  },
  setup () {
    const chartRoomName = ref("图片盒子")
    const currentGroup = ref({})
    const showPopover = ref(false)
    const { toClipboard } = useClipboard()
    const active = ref('')
    const message = ref('')
    const msgList = ref([])
    const onlineUserList = ref([])
    const user = ref({})
    const online = ref(false)
    const showOnlineUserPopup = ref(false)
    // var heartbeatTimer = null

    const msgPopup = ref({
      show: false,
      actions: [{ name: '复制消息' }],
      message: {}
    })
    const imgPopup = ref({
      show: false,
      src: ''
    })
    const loginPopup = ref({
      show: false,
      login: {
        account: '',
        password: ''
      },
      regist: {
        account: '',
        password: '',
        nickName: ''
      }
    })


    var signal_socket = new SignalR.HubConnectionBuilder()
      .configureLogging(SignalR.LogLevel.Information)
      .withUrl(`${process.env.VUE_APP_SOCKET_BASE_URL}/hubs/chatroomhub`, {
        accessTokenFactory: () => localStorage.getItem("token"),
        skipNegotiation: true,
        transport: SignalR.HttpTransportType.WebSockets
      })
      .withAutomaticReconnect({
        nextRetryDelayInMilliseconds: () => {
          //每5秒重连一次
          return 5000
        }
      })   //自动重连
      .build()


    signal_socket.on("ReciveMessage", msg => {
      console.log("收到消息", msg, new Date())

      switch (msg.type) {
        case 1:
        case 2:
          //只显示最近100条消息
          msgList.value.push(msg)
          if (msgList.value.length > 100) {
            msgList.value.shift()
          }

          nextTick(() => {
            let dom = document.getElementById('aa')
            if (dom) {
              // console.log("1111", new Date())
              dom.scrollIntoView(true);
            }
          })
          break;

        case 101:
          onlineUserList.value = JSON.parse(msg.message)
          break;
        default:
          Notify(msg.message);
          break;
      }
    })

    signal_socket.onclose(async () => {
      // this.$notify({ type: 'danger', message: '信号连接断开' });
      // this.socketStatus.signal = false
      Notify("你掉线了");

      online.value = false
    })
    signal_socket.onreconnecting(() => {
      // this.socketStatus.signalTimer = 1
      // this.socketStatus.signal = false
      Notify("掉线重连中")
      online.value = false
    })
    signal_socket.onreconnected(async () => {
      //重新连接上
      // this.socketStatus.signal = true
      // this.socketStatus.signalTimer = undefined
      console.log("重新连接上")

      Notify("重新连接成功")
      tokenLoginHandle()

    })



    signal_socket.start().then(() => {
      console.log("连接成功")
      tokenLoginHandle()
    }).catch(() => {
      // debugger
      // socketStatus.signal = false
    })


    const tokenLoginHandle = () => {
      var token = localStorage.getItem("token")
      if (token) {
        invoke("TokenLogin").then(res => {
          if (res) {
            loginCompleted(res)
          }
        })
      } else {
        loginPopup.value.show = true
      }
    }

    const loginCompleted = (res) => {

      Notify("登录成功");
      loginPopup.value.show = false
      localStorage.setItem("token", res.token)
      user.value = res
      online.value = true
      joinGroupHandle({ groupName: chartRoomName.value })

      // if (!heartbeatTimer) {
      //   heartbeatTimer = setInterval(() => {
      //     invoke("Heartbeat", { groupName: chartRoomName.value })
      //       .then(res => {
      //         // console.log(`登录`, res)
      //         if (res) {
      //           // loginCompleted(res)
      //           console.log(`心跳`, res)
      //           onlineUserList.value = res
      //         }
      //       }).catch(err => {
      //         //信号订阅失败
      //         return console.log(err.toString());
      //       });
      //   }, 5000);
      // }
    }


    const loginHandle = (values) => {
      invoke("Login", values)
        .then(res => {
          console.log(`登录`, res)
          if (res) {
            loginCompleted(res)

          }
        }).catch(err => {
          //信号订阅失败
          return console.log(err.toString());
        });
    };

    const registHandle = (values) => {
      if (values.account.length < 6) {
        Toast.fail('账号不能少于6个字符');
        return
      }
      if (values.password.length < 8) {
        Toast.fail('密码不能少于8个字符');
        return
      }
      if (values.nickName.length < 3) {
        Toast.fail('昵称不能少于3个字符');
        return
      }
      invoke("Register", values)
        .then(res => {
          console.log(`注册`, res)
          if (res) {
            Notify("注册成功");
            loginPopup.value.show = false
            localStorage.setItem("token", res.token)
            user.value = res
            joinGroupHandle({ groupName: chartRoomName.value })
          }
        }).catch(err => {
          //信号订阅失败
          return console.log(err.toString());
        });
    };

    const joinGroupHandle = (values) => {
      invoke("JoinGroup", values)
        .then(res => {
          if (res) {
            currentGroup.value = res
            chartRoomName.value = res.groupName
          }
        }).catch(err => {
          //信号订阅失败
          return console.log(err.toString());
        });
    };


    const createGroupHandle = (values) => {
      invoke("CreateGroup", values)
        .then(res => {
          if (res) {
            Notify("创建群聊成功");
          }
        }).catch(err => {
          //信号订阅失败
          return console.log(err.toString());
        });
    };

    const invoke = (method, data) => {
      if (data) {
        return signal_socket.invoke(method, JSON.stringify(data), localStorage.getItem("token"))
      } else {
        return signal_socket.invoke(method, localStorage.getItem("token"))
      }
    }

    const sendMessage = () => {
      if (!message.value) {
        Notify("请输入消息");
        return
      }
      invoke("SendMessage", { type: 1, message: message.value, fromGroupId: chartRoomName.value, toGroupId: chartRoomName.value })
        .then(() => {
          message.value = ''
          // if (res) {
          //   Notify("创建群聊成功");
          // }
        }).catch(err => {
          //信号订阅失败
          Notify(err.toString());
          return console.log(err.toString());
        });
    };

    const copyHandle = (message) => {
      try {
        toClipboard(message).then(() => {
          console.log('Copied to clipboard')
        })

      } catch (e) {
        console.error(e)
      }
    };

    const selectMessageHandle = (data) => {
      msgPopup.value.message = data
      msgPopup.value.show = true
    };

    const onSelectMessageAction = (action) => {
      msgPopup.value.show = false
      if (action.name == "复制消息") {
        copyHandle(msgPopup.value.message.message)
      }
    }

    const messageKeyPressHandle = data => {
      if (data.keyCode == 13) {
        sendMessage()
      }
    }

    const afterReadHandle = data => {
      imgPopup.value.show = false
      // console.log(data.content)
      invoke("SendMessage", { type: 2, message: data.content, fromGroupId: chartRoomName.value, toGroupId: chartRoomName.value })
        .then(() => {
          message.value = ''
          // if (res) {
          //   Notify("创建群聊成功");
          // }
        }).catch(err => {
          //信号订阅失败
          Notify(err.toString());
          return console.log(err.toString());
        });
    }

    const onOversize = (file) => {
      console.log(file);
      Toast.fail('图片大小不能超过 1Mb');
    };

    const sendImgSrc = () => {
      if (!imgPopup.value.src) return
      imgPopup.value.show = false
      invoke("SendMessage", { type: 2, message: imgPopup.value.src, fromGroupId: chartRoomName.value, toGroupId: chartRoomName.value })
        .then(() => {

          imgPopup.value.src = ''
          // if (res) {
          //   Notify("创建群聊成功");
          // }
        }).catch(err => {
          //信号订阅失败
          Notify(err.toString());
          return console.log(err.toString());
        });
    }



    return {
      active,
      chartRoomName,
      loginPopup,
      msgPopup,
      loginHandle,
      registHandle,
      signal_socket,
      createGroupHandle,
      sendMessage,
      message,
      msgList,
      user,
      copyHandle,
      selectMessageHandle,
      onSelectMessageAction,
      currentGroup,
      messageKeyPressHandle,
      afterReadHandle,
      onOversize,
      showPopover,
      imgPopup,
      sendImgSrc,
      online,
      onlineUserList,
      showOnlineUserPopup
    }
  }
}
</script>
<style scoped>
.home {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background: #f7f8fa;
}
.title {
  text-align: center;
  padding: 10px 0;
}
.content {
  position: fixed;
  top: 40px;
  bottom: 50px;
  left: 0;
  right: 0;
  overflow-y: auto;
}
.footer {
  position: fixed;
  display: flex;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: rgb(251 250 250 / 35%);
  padding: 10px;
  box-sizing: border-box;
}
.footer input {
  border: 1px solid #e1e1e1;
  background: #fff;
  height: 29px;
  line-height: 29px;
  width: 100%;
}

.card {
  background: #fff;
  border-radius: 10px;
  padding: 10px;
  margin: 10px;
}
.card .message {
  flex: 1;
  padding-bottom: 10px;
  word-break: break-word;
  /* background: #fff;
  border-radius: 10px;
  padding: 10px;
  margin: 10px; */
}

.card .message img {
  width: 100%;
  border-radius: 10px;
}
.chat-info {
  padding-top: 10px;
  font-size: 12px;
  font-weight: 500;
  color: #8d8d8d;
}
.chat-info span {
  margin-right: 4px;
}

.chat-info span:last-child {
  margin-right: 0;
}
.card.right {
  background: #07c160;
  color: #fff;
}
.card.right .chat-info {
  color: #fff;
}

.right .chat-info {
  text-align: right;
}

.img-popup-warpper >>> .van-cell__value {
  flex: initial;
}
.img-popup-warpper >>> .van-field__value {
  width: 100%;
}
</style>